<?php

namespace app\common\model\banxi\trainer;

use app\common\model\common\BaseModel;
use think\exception\ValidateException;
use think\Model;
use think\model\concern\SoftDelete;

/**
 * 教练头衔
 */
class TrainerTitle extends BaseModel
{

    use SoftDelete;

    protected $name = 'banxi_trainer_title';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'sortNum' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];


    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------


    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------


    public function getListPage(array $where, string $page = "1", int $limit = 10)
    {
        return $this->withCount(['trainerNum' => 'trainerNum'])->where($where)
            ->order(['id' => 'desc'])
            ->paginate([
                'page' => $page,
                'list_rows' => $limit,
            ]);
    }

    public function getListSelectPage(array $where, string $page = "1", int $limit = 10)
    {
        return $this->where($where)
            ->order(['id' => 'desc'])
            ->paginate([
                'page' => $page,
                'list_rows' => $limit,
            ]);
    }


    public function getInfo(array $where): array|Model|null
    {
        return $this->withCount(['trainerNum' => 'trainerNum'])->where($where)->find();
    }

    public function saveOrUpdate(array $data): bool
    {
        $id = $data['id'] ?? null;
        if ($id == null) {
            $gradeModel = new self();
            $gradeModel->save($data);
        } else {
            $gradeModel = self::where('id', $id)->find();
            if (empty($gradeModel)) {
                throw new ValidateException('教练头衔不存在');
            }
            $gradeModel->save($data);
        }
        return true;
    }

    public function del(array $ids)
    {
        return self::destroy(function ($query) use ($ids) {
            $query->whereIn('id', $ids);
        });

    }

    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------

    public function trainerNum()
    {
        return $this->hasMany(Trainer::class, 'title', 'id');
    }
}